package com.example.core.arch.advice;

import com.alibaba.fastjson.JSONObject;
import com.example.core.arch.annotation.AutoSetter;
import com.example.core.arch.baseData.Status;
import com.example.core.entity.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.*;

@Slf4j
@Aspect
@Component
public class AutoSetterAdvice {

    @Pointcut("execution(* com.example.core.mapper.*Mapper.*(..))")
    public void point(){

    }

    /**
     * BaseEntity设置默认参数,采用前置通知
     */
    @Before("point() && @annotation(com.example.core.arch.annotation.AutoSetter)")
    public void before(JoinPoint jointPoint) {
        Object[] args = jointPoint.getArgs();

        AutoSetter autoSetter = ((MethodSignature) jointPoint.getSignature()).getMethod().getAnnotation(AutoSetter.class);
        if (args == null || args.length == 0) {
            return;
        }
        for (Object arg : args) {
            if (arg instanceof BaseEntity) {
                BaseEntity entity = (BaseEntity) arg;
                List<String> values = new ArrayList<>(Arrays.asList(autoSetter.value()));
                if (CollectionUtils.isEmpty(values)) {
                    return;
                }
                values.forEach(value -> handle(entity, value));
            }
        }
    }

    private void handle(BaseEntity entity, String value) {
        Field field = null;
        try {
            field = entity.getClass().getDeclaredField(value);
            ReflectionUtils.makeAccessible(field);
        } catch (NoSuchFieldException e) {
            return;
        }
        String typeName = field.getType().getSimpleName();

        if (Date.class.getSimpleName().equals(typeName)) {
            ReflectionUtils.setField(field, entity, Calendar.getInstance().getTime());
        } else if (Integer.class.getSimpleName().equals(typeName)) {
            ReflectionUtils.setField(field, entity, 0);
        }
    }
}
